/*
 * <p>Title:       箄1�7单的标题</p>
 * <p>Description: 稍详细的说明</p>
 * <p>Copyright:   Copyright (c) 2004</p>
 * <p>Company:     东软集团股份有限公司</p>
 */
package com.ll.core.httpbase;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

	private String address;
	private URL url;
	private HttpURLConnection httpconnection;
	private HttpRequest<Object, Object> request;

	private HttpHandler dealHander;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public URL getUrl() {
		return url;
	}

	public void setUrl(URL url) {
		this.url = url;
	}

	public HttpRequest getRequest() {
		return request;
	}

	public void setRequest(HttpRequest request) {
		this.request = request;
	}

	public HttpUtil() {
		dealHander = new DefaultHttpHandlerImpl(this);
		this.request = new HttpRequest<Object, Object>();
	}

	public HttpUtil(String address) {
		this();
		this.address = address;
	}

	public void addParameter(Object key, Object value) {
		this.request.addParameter(key, value);
	}

	public void removeParameter(Object key) {
		this.request.removeParameter(key);
	}

	public HttpURLConnection getHttpconnection() {
		return httpconnection;
	}

	public HttpResponse sendrequest() {
		return this.sendrequest(null);
	}

	public HttpResponse sendrequest(HttpRequest rs) {
		try {
			this.url = new URL(this.address);
			this.httpconnection = (HttpURLConnection) this.url.openConnection();
			// 设置相关参数
			this.dealHander.beforerequest(httpconnection);
			
			// 设置是否可以输出
			//设置请求参数
			if (rs == null) {
				this.dealHander.sendRequesthandler(this.httpconnection, this.getRequest());
			} else {
				this.dealHander.sendRequesthandler(this.httpconnection, rs);
			}
			//发送请求
			// 接收结果
			HttpResponse hs = dealHander.getResponsehandler(httpconnection);
			return hs;
		} catch (Exception e) {
			HttpResponse hs = new HttpResponse();
			hs.setErrorMessage(e.getMessage());
			hs.setCode(-1);
			return hs;

		}
	}

	
}
